package com.lx.note.web;

import com.lx.common.constant.SessionConstant;
import com.lx.note.entity.UserBO;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限过滤器,判断用户是否登录,如果未登录 ,则将请求重定向到登录页
 * Created by Administrator on 2018/5/24 0024.
 */
public class AccessFilter implements Filter{
    final private static String URI_LOGIN= "/log_in.html";
    final private static String URI_ALERT = "/alert/";


    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //数据类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //判断访问的资源路径是否需要登录权限
        String path = req.getRequestURI();
        if( path.endsWith(URI_LOGIN)|| path.contains(URI_ALERT)){
            //设置 http协议头,避免浏览器缓存html页面
            resp.addHeader("Cache-Control", "no-cache");
            chain.doFilter(request, response);
            return;
        }

        //对于需要权限限制的资源
        //判断是否已登录
        UserBO userBo = (UserBO) req.getSession().getAttribute(SessionConstant.KEY_LOGIN_USER);
        if(userBo ==null){
            //如锅userBo 为null 则表示没有登录
            //重定向到 login_in.html
            //采用绝对路径重定向,尽可能避免错误
            String login = req.getContextPath() + URI_LOGIN;
            resp.sendRedirect(login);
            return;
        }
        //设置 http协议头,避免浏览器缓存html页面
        resp.addHeader("Cache-Control", "no-cache");
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}
